# !/usr/bin/env python3
# coding: utf-8
# File: MedicalGraph.py
# Date: 18-10-3

import os
import json

class MedicalGraph:
    def __init__(self,datas):
        cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])
        self.data_path = os.path.join(cur_dir, 'data/jsonFile.json')
        self.datas = datas
        #self.g = Graph("http://localhost:7474", auth=("neo4j", "mrdl7824"), name="neo4j")

    '''读取文件'''


    def read_nodes(self):
        # 共７类节点
        movies = []  # 电影
        actors = []  # 演员
        directors = []  # 导演
        types = []  # 类型
        years = []  # 拍摄年份
        countrys = []  # 国家
        appraises = ["1", "2", "3", "4", "5"]  # 评价星级

        #disease_infos = []  # 疾病信息

        # 构建节点实体关系
        rels_actor = []     # 电影---（相关演员）---》演员 关系
        rels_director = []  # 电影---(相关导演)---》导演 关系
        rels_filming = []   # 导演---（拍摄）---》电影 关系
        rels_act = []   # 演员---（扮演）---》电影 关系
        rels_fromCountry = []   # 电影---（所属国家）---》国家 关系
        rels_typeR = []  # 电影---（所属类型）---》类型 关系
        rels_beAppraise = []    # 电影---（被评价）---》评价星级 关系
        rels_playYear = []      # 电影---(拍摄于)---》年份 关系
        rels_toAppraise = []    # 评价星级---（评价）---》电影 关系
        rels_sameYear = []      # 年份---（同年拍摄）---》电影 关系
        rels_sameType = []      # 类型---（相同类型）---》电影 关系
        rels_sameCountry = []   # 国家---（相同国家）---》电影 关系
        # rels_noteat = []  # 疾病－忌吃食物关系
        # rels_doeat = []  # 疾病－宜吃食物关系
        # rels_recommandeat = []  # 疾病－推荐吃食物关系
        # rels_commonddrug = []  # 疾病－通用药品关系
        # rels_recommanddrug = []  # 疾病－热门药品关系
        # rels_check = []  # 疾病－检查关系
        # rels_drug_producer = []  # 厂商－药物关系
        #
        # rels_symptom = []  # 疾病症状关系
        # rels_acompany = []  # 疾病并发关系
        # rels_category = []  # 疾病与科室之间的关系

        count = 0
        for data in self.datas:
            print(data)
            movie_dict = {}
            count += 1
            print(count)

            #data_json = json.loads(data)

            movie = data['name']
            movie_dict['name'] = movie
            movies.append(movie)
            movie_dict['desc'] = ''
            movie_dict['prevent'] = ''
            movie_dict['cause'] = ''
            movie_dict['easy_get'] = ''
            movie_dict['cure_department'] = ''
            movie_dict['cure_way'] = ''
            movie_dict['cure_lasttime'] = ''
            movie_dict['symptom'] = ''
            movie_dict['cured_prob'] = ''

            if 'director' in data:
                directors .append(data['director'])      # 先添加到导演集合里
                rels_director.append([movie, data['director']])
                rels_filming.append([data['director'], movie])

            if 'year' in data:
                years .append(data['year'])
                rels_playYear.append([movie, data['year']])
                rels_sameYear.append([data['year'], movie])

            if 'country' in data:
                countrys .append(data['country'])
                rels_fromCountry.append([movie, data['country']])
                rels_sameCountry.append([data['country'], movie])

            if 'type' in data:
                types .append(data['type'])
                rels_typeR.append([movie, data['type']])
                rels_sameType.append([data['type'], movie])

            if 'actor' in data:
                actors .append(data['actor'])
                rels_actor.append([movie, data['actor']])
                rels_act.append([data['actor'], movie])

            if 'appraise' in data:
                fNum = float(data['appraise'])
                if fNum > 8.0:
                    rels_beAppraise.append([movie, "5"])
                    rels_toAppraise.append(["5", movie])
                elif fNum > 6.0:
                    rels_beAppraise.append([movie, "4"])
                    rels_toAppraise.append(["4", movie])
                elif fNum > 4.0:
                    rels_beAppraise.append([movie, "3"])
                    rels_toAppraise.append(["3", movie])
                elif fNum > 2.0:
                    rels_beAppraise.append([movie, "2"])
                    rels_toAppraise.append(["2", movie])
                else:
                    rels_beAppraise.append([movie, "1"])
                    rels_toAppraise.append(["1", movie])

        print(movies)
        years = list(set(years))
        print(years)
        print(len(years))
        countrys = list(set(countrys))
        print(countrys)
        print(len(countrys))
        types = list(set(types))
        print(types)
        print(len(types))
        actors = list(set(actors))
        print(actors)
        print(len(actors))
        print(rels_director)
        print(len(rels_director))
        print(rels_playYear)
        print(len(rels_playYear))
        print(rels_fromCountry)
        print(len(rels_fromCountry))
        print(rels_typeR)
        print(len(rels_typeR))
        print(rels_actor)
        print(len(rels_actor))
        print(rels_beAppraise)
        print(len(rels_beAppraise))
        return movies, actors, directors, countrys, years, types, appraises, \
               rels_actor, rels_director, rels_filming, rels_act, rels_fromCountry, rels_typeR, rels_beAppraise, rels_playYear, \
               rels_toAppraise, rels_sameYear, rels_sameType, rels_sameCountry

    # def create_node(self, label, nodes):
    #     count = 0
    #     for node_name in nodes:
    #         node = Node(label, name=node_name)
    #         self.g.create(node)
    #         count += 1
    #         print(count, len(nodes))
    #     return

    # def create_diseases_nodes(self, disease_infos):
    #     count = 0
    #     for disease_dict in disease_infos:
    #         node = Node("Movie", name=disease_dict['name'], director=disease_dict['director'],
    #                     actor=disease_dict['actor'], country=disease_dict['country'],
    #                     year=disease_dict['year'], type=disease_dict['type'],
    #                     appraise=disease_dict['appraise'])
    #         self.g.create(node)
    #         count += 1
    #         print(count)
    #     return



    def create_graphnodes(self):
        movies, actors, directors, countrys, years, types, appraises, rels_actor, rels_director, rels_filming, rels_act, rels_fromCountry, rels_typeR, rels_beAppraise, rels_playYear, rels_toAppraise, rels_sameYear, rels_sameType, rels_sameCountry = self.read_nodes()
        self.create_diseases_nodes(self.datas)
        self.create_node('Director', directors)
        print(len(directors))
        self.create_node('Actor', actors)
        print(len(actors))
        self.create_node('Country', countrys)
        print(len(countrys))
        self.create_node('Year', years)
        print(len(years))
        self.create_node('Type', types)
        print(len(types))
        self.create_node('Appraise', appraises)
        return

    def create_graphrels(self):
        Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos, rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug, rels_symptom, rels_acompany, rels_category = self.read_nodes()
        self.create_relationship('Disease', 'Food', rels_recommandeat, 'recommand_eat', '推荐食谱')
        self.create_relationship('Disease', 'Food', rels_noteat, 'no_eat', '忌吃')
        self.create_relationship('Disease', 'Food', rels_doeat, 'do_eat', '宜吃')
        self.create_relationship('Department', 'Department', rels_department, 'belongs_to', '属于')
        self.create_relationship('Disease', 'Drug', rels_commonddrug, 'common_drug', '常用药品')
        self.create_relationship('Producer', 'Drug', rels_drug_producer, 'drugs_of', '生产药品')
        self.create_relationship('Disease', 'Drug', rels_recommanddrug, 'recommand_drug', '好评药品')
        self.create_relationship('Disease', 'Check', rels_check, 'need_check', '诊断检查')
        self.create_relationship('Disease', 'Symptom', rels_symptom, 'has_symptom', '症状')
        self.create_relationship('Disease', 'Disease', rels_acompany, 'acompany_with', '并发症')
        self.create_relationship('Disease', 'Department', rels_category, 'belongs_to', '所属科室')

    def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
        count = 0
        # 去重处理
        set_edges = []
        for edge in edges:
            set_edges.append('###'.join(edge))
        all = len(set(set_edges))
        for edge in set(set_edges):
            edge = edge.split('###')
            p = edge[0]
            q = edge[1]
            query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
                start_node, end_node, p, q, rel_type, rel_name)
            try:
                self.g.run(query)
                count += 1
                print(rel_type, count, all)
            except Exception as e:
                print(e)
        return

if __name__ == '__main__':
    f = open('data/jsonFile.json',encoding="utf-8")
    jsonList = json.load(f)
    print(jsonList)
    handler = MedicalGraph(datas=jsonList)
    handler.read_nodes()